import Vue from 'vue';
import App from './App.vue';
import router from './router/index';
import ElementUI from 'element-ui';


import 'element-ui/lib/theme-chalk/index.css'; // 默认主题
// import './assets/css/theme-green/index.css'; // 浅绿色主题
import './assets/css/icon.css';
import './components/common/directives';
import 'babel-polyfill';
import store from './store'

import "@/svgIcon/index.js";

import 'default-passive-events';

import '@/assets/icon/iconfont.css'

import 'video.js/dist/video-js.css'

// 上传、下载、导出进度条
import 'nprogress/nprogress.css';
import Cookies from 'js-cookie';

import qs from 'qs';
Vue.prototype.$qs = qs;


//入口index.js
import player from 'vue-hls-player'
Vue.use(player)

console.log(require('@/lang/zh.js'), )
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
// import { messages } from './components/common/';
const i18n = new VueI18n({
    locale: 'zh', // 默认简体中文
    messages: {
        'zh': require('@/lang/zh.js'), // 中文语言包
        'en': require('@/lang/en.js') // 英文语言包
    }
});
Vue.config.productionTip = false;

Vue.use(ElementUI, {
    size: 'small'
});

import * as utils from '@/utils/utils';
console.log(utils)
for (var key in utils) {
    Vue.prototype['$' + key] = utils[key];
}

import request from '@/utils/request'

Vue.prototype.$http = request;
// 后端多端口服务 每个都要拦截
for (var i = 0, len = request.length; i < len; i++) {
    // 默认post请求头为application/json
    request[i].defaults.headers.post['Content-Type'] = "application/json";
    request[i].interceptors.request.use(
        config => {
            // let token = store.state.app.token;
            // token && (config.headers.Token = `${token}`);
            // clearHttpRequestingList()
            if (Cookies.get('access_token')) {
                config.headers['Authorization'] = 'Bearer ' + Cookies.get('access_token')
                console.log('请求报文', config);
                localStorage.setItem('id', '1')
                localStorage.setItem('code', 'pms')
                config.headers['region'] = localStorage.getItem('region')
                config.headers['channel'] = localStorage.getItem('channel')
            } else if (Cookies.get('refresh_token')) {
                config.headers['Authorization'] = 'Bearer ' + Cookies.get('refresh_token')
                console.log('请求报文', config);
                localStorage.setItem('id', '1')
                localStorage.setItem('code', 'pms')
                config.headers['region'] = localStorage.getItem('region')
                config.headers['channel'] = localStorage.getItem('channel')
            } else {
                // 跳转登录
                router.replace({
                    path: '/login',
                }).catch(err => {})
            }

            return config;
        },
        error => {
            console.log(error);
            return Promise.reject(error);
        }
    );

    request[i].interceptors.response.use(
        response => {
            console.log('响应报文', response);
            // 3001表示token过期失效
            if (response.data.code == '3001') {
                Vue.prototype.$message.error({
                    message: response.data.message,
                    duration: 1500
                });
                Cookies.remove('access_token');
                Cookies.remove('refresh_token');
                router.replace({
                    path: '/login',
                }).catch(err => {})
            }
            return response;
        },
        error => {
            console.dir(error);
            return Promise.reject(error);
        }
    );
}

// 使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    console.log(to.meta.title, to.name, to.meta.requireAuth);
    document.title = to.meta.title || '万声音乐';
    if (to.meta.requireAuth) {
        if (!(Cookies.get('access_token') || Cookies.get('refresh_token'))) {
            return next({
                path: '/login'
            });
        }
    }
    // console.log(66666, to.name)
    // 已登录的情况再去登录页，跳转至首页
    if (to.name === 'Login') {
        if (Cookies.get('access_token') || Cookies.get('refresh_token')) {
            return next({
                path: '/' // 相当于跳转到 /quku/survey
            })
        }
    }
    // console.log(66666, to.name)

    next()
});


console.log(88888)
import { asyncRoutes, otherRoutes } from '@/router/routerGroup'
try {
    console.log(1111)
    async function getSidebarData() {
        try {
            const url = '/user/menus';
            const { data: res } = await request[4].get(url, {
                params: ({
                    serviceId: localStorage.getItem('code')
                })
            });
            console.log('侧边栏111', res);
            if (res.code != '0000') {
                throw new Error(res.message);
            }
            store.commit('SET_SLIDEBAR_DATA', res.data)
                // next({ path: to.path || '/' })

            function generateRoutes(data) {
                console.log(data)
                var result = []
                data.forEach(item => {
                        if (item.permissions) {
                            item.permissions.forEach(item_ => {
                                if (asyncRoutes[item_.name]) result.push(asyncRoutes[item_.name])
                            })
                        }
                    })
                    // console.log(result)
                    // 最后添加404页面 否则会在登陆成功后跳到404页面
                result.push({ path: '*', redirect: '/404' }, )
                return result;
            }
            const routes = generateRoutes(res.data).length > 0 ? generateRoutes(res.data) : [...Object.values(asyncRoutes)]
            console.log(routes);
            // 动态添加路由
            // router.addRoutes(routes)
            router.addRoutes([{
                // 一级路由组件
                path: '/',
                // redirect: '/quku/survey',
                component: () =>
                    import ( /* webpackChunkName: "home" */ '@/components/common/Home.vue'),
                meta: { title: '自述文件', requireAuth: true, keepAlive: true },
                // 二级路由组件
                children: [...otherRoutes, ...routes]
            }, ])


        } catch (err) {
            console.dir(err);
        }
    }
    getSidebarData()
} catch (err) {
    console.log(err)
}
/* 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面 */
// router.onError((error) => {
//     const pattern = /Loading chunk (\d)+ failed/g;
//     const isChunkLoadFailed = error.message.match(pattern);
//     const targetPath = router.history.pending.path;
//     if (isChunkLoadFailed) {
//         router.replace(targetPath);
//     }
// });

console.log(router);


new Vue({
    router,
    store,
    i18n,
    render: h => h(App)
}).$mount('#app');